/*
 File: SVNXRecentMessage.m
 
 Copyright (c) <2010>, <yoyokko@gmail.com>
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 
 Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the 
 following disclaimer in the documentation and/or other materials provided with the distribution.
 Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or 
 promote products derived from this software without specific prior written permission.
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 
 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 */

#import "SVNXRecentMessage.h"


@implementation SVNXRecentMessage

- (void) LoadUI
{
	[NSBundle loadNibNamed:@"Panel" owner:self];
}

- (id) init
{
	if(self = [super init])
	{
		[self LoadUI];
	}
	return self;
}

- (void) dealloc
{
	[self setPopupMenu:nil];
	[super dealloc];
}

- (BOOL) hasRowSelected {
	int row = [recentMessageTableView selectedRow];
	if(row >= 0)
		return YES;
	else
		return NO;
}

- (void) setHasRowSelected: (BOOL) newValue {
	hasRowSelected = newValue;
}

- (IBAction) cancelRecentMessage:(id) sender
{
	[recentMessageWindow close];
}

- (IBAction) insertRecentMessage:(id) sender
{
	if(![self hasRowSelected])
	{
		NSRunAlertPanel(@"Error", @"Please select a row.", @"OK", nil, nil);
		return;
	}
	NSData *recentMessageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessages"];
	NSDictionary *recentMessageDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageData];
	NSString *recentMessageString = [recentMessageDict objectForKey:[NSNumber numberWithInt:[recentMessageTableView selectedRow]]];
	if(recentMessageString)
	{
		[[self commitTextView] setString:recentMessageString];
	}
	
	[recentMessageWindow close];
}

- (IBAction) openRecentMessageWindow:(id) sender
{
	//[recentMessageWindow makeKeyAndOrderFront:nil];
	[self constructPopupMenu];
	NSEvent *currentMouseEvent = [[NSApplication sharedApplication] currentEvent];
	[NSMenu popUpContextMenu:[self popupMenu] withEvent:currentMouseEvent forView:sender];
}

- (void) menuItemSelected:(id) sender
{
	NSData *recentMessageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessages"];
	NSDictionary *recentMessageDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageData];
	NSString *recentMessageString = [recentMessageDict objectForKey:[sender title]];
	if(recentMessageString)
	{
		[[self commitTextView] setString:recentMessageString];
	}
}

- (void) clearAllHistories
{
	int result = NSRunAlertPanel(@"Warning", @"Are you sure to remove all message histories?", @"YES", @"NO", @"");
	if(result == NSOKButton)
	{
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"RecentMessagesTime"];
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"RecentMessages"];
		[[NSUserDefaults standardUserDefaults] synchronize];
	}
}

- (void) constructPopupMenu
{
	[self setPopupMenu:nil];
	[self setPopupMenu:[[[NSMenu alloc] init] autorelease]];
	
	NSData *recentMessageTimeData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessagesTime"];
	NSDictionary *recentMessageTimeDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageTimeData];
	
	if(!recentMessageTimeDict)
	{
		[[self popupMenu] insertItemWithTitle:@"No recent messages." action:NULL keyEquivalent:@"" atIndex:0];
		return;
	}
	
	NSArray *messageTime = [recentMessageTimeDict allKeys];
	int index = 0;
	for (NSDateComponents *components in messageTime) {
		NSString *componentString = [NSString stringWithFormat:@"%d-%d-%d", [components year], [components month], [components day]];
		NSMenuItem *timeItem = [[NSMenuItem alloc] init];
		[timeItem setTitle:componentString];
		[timeItem setSubmenu:[[[NSMenu alloc] init] autorelease]];
		NSArray *allMessageKeys = [(NSMutableDictionary *)[recentMessageTimeDict objectForKey:components] allKeys];
		int count = [allMessageKeys count];
		for (int i = 0; i < count; i++) {
			NSMenuItem *item = [[NSMenuItem alloc] init];
			[item setTitle:[allMessageKeys objectAtIndex:i]];
			[item setAction:@selector(menuItemSelected:)];
			[item setTarget:self];
			[[timeItem submenu] insertItem:item atIndex:i];
			[item release];
		}
		[[self popupMenu] insertItem:timeItem atIndex:index++];
	}
	
	[[self popupMenu] insertItem:[NSMenuItem separatorItem] atIndex:index++];
	
	NSMenuItem *removeHistory = [[NSMenuItem alloc] init];
	[removeHistory setTitle:@"Remove all recent messages."];
	[removeHistory setTarget:self];
	[removeHistory setAction:@selector(clearAllHistories)];
	[[self popupMenu] insertItem:removeHistory atIndex:index++];
	[removeHistory release];
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
	NSData *recentMessageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessages"];
	NSDictionary *recentMessageDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageData];
	if(recentMessageDict)
	{
		return [recentMessageDict count];
	}else
	{
		return 0;
	}
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	if(aTableColumn == messageColumn)
	{
		NSData *recentMessageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessages"];
		NSDictionary *recentMessageDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageData];
		if(recentMessageDict)
			return [(NSString *)[recentMessageDict objectForKey:[NSNumber numberWithInt:rowIndex]] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
		else
			return nil;
	}else
	{
		NSData *recentMessageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"RecentMessagesTime"];
		NSDictionary *recentMessageTimeDict = [NSKeyedUnarchiver unarchiveObjectWithData:recentMessageData];
		if(recentMessageTimeDict)
			return [recentMessageTimeDict objectForKey:[NSNumber numberWithInt:rowIndex]];
		else
			return nil;
	}
}


- (NSTextView *) commitTextView {
	return commitTextView;
}

- (void) setCommitTextView: (NSTextView *) newValue {
	[commitTextView autorelease];
	commitTextView = [newValue retain];
}


- (NSButton *) recentMessageButton {
	return recentMessageButton;
}


- (NSWindow *) baseWindow {
	return baseWindow;
}

- (void) setBaseWindow: (NSWindow *) newValue {
	[baseWindow autorelease];
	baseWindow = [newValue retain];
}


- (NSMenu *) popupMenu {
	return popupMenu;
}

- (void) setPopupMenu: (NSMenu *) newValue {
	if(popupMenu != newValue)
	{
		[popupMenu release];
		popupMenu = [newValue retain];
	}
}

@end
